package cube.net.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import cube.utils.BaseUtil;

/**
 * TCP服务端（等待连接请求）
 * 
 * @author abiao
 */
public class SocketServer {

    /**
     * 连接池，保存客户端与服务端建立的长连接
     */
    private SocketConnPool conns = new SocketConnPool();
    private ServerSocket ssk;

    private int port;

    /**
     * Socket服务端
     */
    public SocketServer(int port) {
        this.port = port;
    }

    /**
     * 启动服务器
     */
    public void start() {
        new Thread() {
            public void run() {
                listen();
            }
        }.start();
    }

    /**
     * 监听连接请求
     */
    private void listen() {
        try {
            ssk = new ServerSocket(port);
            startSuccess();
            while (true) {
                handleSocket(ssk.accept());
            }
        } catch (IOException e) {
            startFailure(e);
        }
    }

    /**
     * 启动成功
     */
    public void startSuccess() {
        BaseUtil.msg.debug("socket.server.start.success", port);
    }

    /**
     * 启动失败
     */
    public void startFailure(Exception e) {
        BaseUtil.msg.error("socket.server.start.failure", port);
    }

    /**
     * 套接字处理
     */
    private void handleSocket(Socket socket) {
        SocketConnect conn = new SocketConnectImpl(socket) {
            public void recv(SocketConnect conn, byte[] data) {
                SocketServer.this.recv(conn, data);
            }
        };
        conns.add(conn);
        this.accept(conn);
    }

    /**
     * 建立连接
     */
    public void accept(SocketConnect conn) {
        BaseUtil.msg.debug("socket.connect.accept", conn);
    }

    /**
     * 接收数据
     */
    public void recv(SocketConnect conn, byte[] data) {
        this.recv(data);
    }

    /**
     * 接收数据
     */
    public void recv(byte[] data) {
    }

    /**
     * 获取Socket连接
     */
    public SocketConnect getConnect(String ip, int port) {
        return conns.get(ip, port);
    }

    /**
     * 返回所有连接
     */
    public List<SocketConnect> getAllConnects() {
        return conns.getAllConnects();
    }

    /**
     * 关闭服务端
     */
    public void close() {
        try {
            for (SocketConnect conn : getAllConnects()) {
                conn.close();
            }
            ssk.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
